package vip.xiaonuo.modular.config;

import com.anji.captcha.service.CaptchaCacheService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author liu
 */
public class CaptchaCacheServiceImpl implements CaptchaCacheService {

    @Resource
    private RedissonClient redissonClient;

//    @Value("${aj.captcha.cache-type}")

//    private static String cacheType;

    @Override
    public void set(String key, String value, long expiresInSeconds) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value);
        bucket.expire(expiresInSeconds, TimeUnit.SECONDS);
    }


    @Override
    public boolean exists(String key) {
        return redissonClient.getBucket(key).isExists();
    }

    @Override
    public void delete(String key) {
        redissonClient.getBucket(key).delete();
    }

    @Override
    public String get(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    @Override
    public String type() {
        return "redis";
    }

    @Override
    public Long increment(String key, long val) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        Long ret = Long.parseLong(bucket.get()) + val;
        bucket.set(ret + "");
        bucket.expire(0L, TimeUnit.SECONDS);
        return ret;
    }
}
